package gestioneContesto;

import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class GestoreContesto {

	private static Context getInitialContext() throws NamingException {

		Properties p = new Properties();
		p.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
		p.put("java.naming.provider.url", "jnp://localhost:1099");
		p.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");

		return new javax.naming.InitialContext(p);

	}

	public <T> T getGestore(Class<T> interfaccia, String nomeClasse) throws NamingException {

		Context jndiContext = getInitialContext();
		Object ref = jndiContext.lookup(nomeClasse);

		@SuppressWarnings("unchecked")
		T gestore  = (T) PortableRemoteObject.narrow(ref, interfaccia);

		return gestore;

	}
	
	//Formatter: ritorna una Date da una String
	public Date formattaData(String data) {
		
		String supporto = new String();
		int anno = Integer.parseInt(data.substring(0, data.indexOf("-"))); //formato standard per le date
		supporto = data.substring(data.indexOf("-") + 1);
		int mese = Integer.parseInt(supporto.substring(0, supporto.indexOf("-")));
		supporto = supporto.substring(supporto.indexOf("-") + 1);
		int giorno = Integer.parseInt(supporto.substring(0, supporto.indexOf(" ")));
		supporto = supporto.substring(supporto.indexOf(" ") + 1);
		int ora = Integer.parseInt(supporto.substring(0, supporto.indexOf(":")));
		supporto = supporto.substring(supporto.indexOf(":") + 1);
		int minuti = Integer.parseInt(supporto.substring(0, supporto.indexOf(":")));
		supporto = supporto.substring(supporto.indexOf(":") + 1);
		int secondi = Integer.parseInt(supporto.substring(0, supporto.indexOf(".")));
		
		@SuppressWarnings("deprecation")
		Date date = new Date((anno - 1900), (mese - 1), giorno, ora, minuti, secondi);
		return date;
		
	}
	
	@SuppressWarnings("deprecation")
	public Date dataDaInt(int gg, int mm, int aa) {
		
		return new Date((aa - 1900), (mm - 1), gg);
		
	}
	
	//Metodo che calcola la data e l'ora corrente
	public Date dataCorrente() {
		
		int anno = Calendar.getInstance().get(Calendar.YEAR);
		int mese = Calendar.getInstance().get(Calendar.MONTH);
		int giorno = Calendar.getInstance().get(Calendar.DATE);
		int ore = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		int minuti = Calendar.getInstance().get(Calendar.MINUTE);
		int secondi = Calendar.getInstance().get(Calendar.SECOND);
		
		@SuppressWarnings("deprecation")
		Date date = new Date((anno - 1900), mese, giorno, ore, minuti, secondi);
		return date;
		
	}

}
